package co.gov.medellin.ssti.sub.web.action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.beans.factory.annotation.Autowired;

import co.gov.medellin.ssti.sub.common.excepcion.SUBException;
import co.gov.medellin.ssti.sub.common.util.Utility;
import co.gov.medellin.ssti.sub.model.dao.exception.DAOException;
import co.gov.medellin.ssti.sub.model.service.BeneficiarioService;
import co.gov.medellin.ssti.sub.model.vo.BeneficiarioVO;
import co.gov.medellin.ssti.sub.paoyer.administration.exception.AdministrationUserException;
import co.gov.medellin.ssti.sub.paoyer.administration.model.vo.UserVO;
import co.gov.medellin.ssti.sub.paoyer.administration.util.AccessControl;
import co.gov.medellin.ssti.sub.paoyer.common.exception.CommonUserException;
import co.gov.medellin.ssti.sub.paoyer.common.exception.UserException;
import co.gov.medellin.ssti.sub.web.form.IngresarBeneficiarioForm;

public class IngresarBeneficiarioAction extends Action {
	@Autowired
	BeneficiarioService beneficiarioServiceImpl;

	/**
	 * This is the main action called from the Struts framework.
	 * 
	 * @param mapping
	 *            The ActionMapping used to select this instance.
	 * @param form
	 *            The optional ActionForm bean for this request.
	 * @param request
	 *            The HTTP Request we are processing.
	 * @param response
	 *            The HTTP Response we are processing.
	 * @return
	 * @throws java.io.IOException
	 * @throws javax.servlet.ServletException
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		ActionMessages messages = new ActionMessages();

		try {
			AccessControl access = new AccessControl();
			access.validateAccess(mapping, request, response);

			BeneficiarioVO objBeneVO = new BeneficiarioVO();
			IngresarBeneficiarioForm buscarForm = (IngresarBeneficiarioForm) form;
			String strDocumento = buscarForm.getDocumento();
			HttpSession session = request.getSession();
			// request.setAttribute("numeroDocumento",strDocumento);
			// request.setAttribute("tipoDocumento",strTipoDocumento);
			session.removeAttribute("beneficiarios");
			session.removeAttribute("Option");
			session.removeAttribute("InsertGrupoFamiliar");
			Collection<BeneficiarioVO> beneficiarios = null;
			session.setAttribute("msg", "");

			if (request.getParameter("search") != null) {
				if (strDocumento != null) {
					objBeneVO.setNumeroDocumento(buscarForm.getDocumento());
					objBeneVO.setTipoDocumento(buscarForm.getTipoDocumento());
					objBeneVO.setNombre1(buscarForm.getPrimer_nombre());
					objBeneVO.setNombre2(buscarForm.getSegundo_nombre());
					objBeneVO.setPrimerApellido(buscarForm.getPrimerApellido());
					objBeneVO.setSegundoApellido(buscarForm
							.getSegundoApellido());
					if (buscarForm.getFechaNacimiento().equals("Dia/Mes/Ano"))
						objBeneVO.setFechaNacimiento("");
					else
						objBeneVO.setFechaNacimiento(buscarForm
								.getFechaNacimiento());

					try {
						beneficiarios = beneficiarioServiceImpl
								.findBeneficiarioByCriteria(objBeneVO,
										"ingresarBeneficiario");
					} catch (DAOException e) {
						SUBException.logDebugError("", e);
					}

					if (beneficiarios != null) { // IF 1
						if (beneficiarios.size() > 0) { // IF 2
							session.setAttribute("beneficiarios", beneficiarios);
							try {
								List<BeneficiarioVO> beneEncontrado = (List<BeneficiarioVO>) beneficiarios;
								BeneficiarioVO beneBDBeneficios = (BeneficiarioVO) beneEncontrado
										.get(0);
								UserVO user = (UserVO) session
										.getAttribute("userInfo");
								String terminalAddress = request
										.getRemoteAddr();
								beneBDBeneficios.setUpdateUser(user.getName());
								beneBDBeneficios.setUpdateTerminal("WEB="
										+ terminalAddress);
								Calendar c = Calendar.getInstance();
								SimpleDateFormat dateFormat = new SimpleDateFormat(
										"dd/MM/yyyy");
								beneBDBeneficios.setUpdateDate(dateFormat
										.format(c.getTime()));
								int guardar = beneficiarioServiceImpl
										.update(beneBDBeneficios);
							} catch (DAOException e) {
								SUBException.logDebugError("", e);
							}
						} else { // END IF 2
							// BUSQUEDA EN SISBEN
							try {
								beneficiarios = beneficiarioServiceImpl
										.findBeneficiarioSisben(objBeneVO);
							} catch (DAOException e) {
								SUBException.logDebugError("", e);
								request.setAttribute(
										"msg",
										"Error en busqueda SISBEN: "
												+ e.getMessage());
							}
							if (beneficiarios != null
									&& beneficiarios.size() > 0) { // IF 3
								List<BeneficiarioVO> beneSisben = (List<BeneficiarioVO>) beneficiarios;
								objBeneVO = (BeneficiarioVO) beneSisben.get(0);
								// CAMBIA EL FORMATO DE TIPO NUMERICO EN EL
								// SISBEN (1,2,3,4) HACIA EL ALFANUMERICO
								// (C,T,R,E)
								request.setAttribute("tipoDocumento", Utility
										.deformatSisbenDocument(objBeneVO
												.getTipoDocumento()));
								request.setAttribute("numeroDocumento",
										objBeneVO.getNumeroDocumento());
								request.setAttribute("nombre1", objBeneVO
										.getNombre1().trim());
								if (objBeneVO.getNombre2() != null)
									request.setAttribute("nombre2", objBeneVO
											.getNombre2().trim());
								else
									request.setAttribute("nombre2",
											objBeneVO.getNombre2());

								request.setAttribute("apellido1", objBeneVO
										.getPrimerApellido().trim());
								if (objBeneVO.getSegundoApellido() != null)
									request.setAttribute("apellido2", objBeneVO
											.getSegundoApellido().trim());
								else
									request.setAttribute("apellido2",
											objBeneVO.getSegundoApellido());
								try {
									String fenato[] = objBeneVO
											.getFechaNacimiento().split("/");
									request.setAttribute("dia", fenato[0]);
									request.setAttribute("mes", fenato[1]);
									request.setAttribute("ano", fenato[2]);
								} catch (Exception err) {
									request.setAttribute("dia", "Dia");
									request.setAttribute("mes", "Mes");
									request.setAttribute("ano", "Ano");
								}
								request.setAttribute("sexo",
										objBeneVO.getSexo());
								request.setAttribute("msg",
										"El beneficiario se ha encontrado en la base de datos del Sisben.");
								request.setAttribute("beneficiarioSisben",
										beneficiarios);
								try {
									Collection<BeneficiarioVO> grupo_familiar = beneficiarioServiceImpl
											.findGrupoFamiliarSisben(
													objBeneVO.getFichaSisben(),
													objBeneVO.getHogar());

									if (grupo_familiar.size() > 0) {
										request.setAttribute("grupo_familiar",
												grupo_familiar);
										session.setAttribute(
												"InsertGrupoFamiliar",
												grupo_familiar);
									}

								} catch (DAOException err) {
									SUBException.logDebugError("", err);
								}
								return mapping.findForward("success");
							} else { // END IF 3
								request.setAttribute("tipoDocumento",
										buscarForm.getTipoDocumento());
								request.setAttribute("numeroDocumento",
										strDocumento);
								request.setAttribute("nombre1",
										buscarForm.getPrimer_nombre());
								request.setAttribute("nombre2",
										buscarForm.getSegundo_nombre());
								request.setAttribute("apellido1",
										buscarForm.getPrimerApellido());
								request.setAttribute("apellido2",
										buscarForm.getSegundoApellido());
								request.setAttribute("dia", buscarForm.getDia());
								request.setAttribute("mes", buscarForm.getMes());
								request.setAttribute("ano", buscarForm.getAno());
								return mapping.findForward("fail");
							}
						}
					} else { // END IF 1
						request.setAttribute("tipoDocumento",
								buscarForm.getTipoDocumento());
						request.setAttribute("numeroDocumento", strDocumento);
						request.setAttribute("nombre1",
								buscarForm.getPrimer_nombre());
						request.setAttribute("nombre2",
								buscarForm.getSegundo_nombre());
						request.setAttribute("apellido1",
								buscarForm.getPrimerApellido());
						request.setAttribute("apellido2",
								buscarForm.getSegundoApellido());
						request.setAttribute("dia", buscarForm.getDia());
						request.setAttribute("mes", buscarForm.getMes());
						request.setAttribute("ano", buscarForm.getAno());
						return mapping.findForward("fail");
					}
				} // FIN IF DOCUMENTO != NULL
			}// FIN IF PRINCIPAL (SEARCH != NULL)
		} catch (UserException ue) {
			messages.add("msgWarn", new ActionMessage("loginForm.message."
					+ ue.getExceptionVO().getId()));
			saveMessages(request, messages);
			if (ue.getExceptionVO().getId() == AdministrationUserException.ENDED_SESSION) {
				response.sendRedirect(request.getContextPath() + "/index.jsp");
			} else if (ue.getExceptionVO().getId() == CommonUserException.NOT_ALLOWED_RESOURCE) {
				response.sendRedirect(request.getContextPath()
						+ "/admin/tile/invalidatedResource.jsp");
			} else {
				return mapping.getInputForward();
			}

		}

		return mapping.findForward("success");
	}
}